package com.vf.cloud.server.signalling;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.vf.cloud.common.constant.Cache;
import com.vf.cloud.common.vo.SignallingVo;
import com.vf.cloud.server.signalling.server.Server;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SignallingServer {

	private static volatile SignallingServer INSYANCE;

	private Server signallingServer;

	private SignallingServer() {
		signallingServer = new Server();
		signallingServer.reconnect();
	}

	public static SignallingServer getInstance() {
		if (null == INSYANCE) {
			synchronized (SignallingServer.class) {
				if (null == INSYANCE) {
					INSYANCE = new SignallingServer();
				}
			}
		}
		return INSYANCE;
	}

	public void run(SignallingVo config) {
		Cache.signalling = config;
	}
	
	public void run() {
		if (signallingServer != null && Cache.signalling!=null) {
			signallingServer.run();
		}
	}

	public void restart(com.vf.cloud.common.domain.Server server) {
		JSONObject object = JSONObject.parseObject(server.getConfig());
		if (!verify(object)) {
			log.error(String.format("[%s]参数不完整，无法启动。", server.getName()));
			return;
		}
		SignallingVo signalling = new SignallingVo();
		signalling.setId(server.getId());
		signalling.setSignalingInnerIP(object.getString("signalingInnerIP"));
		signalling.setSignalingInnerPort(object.getInteger("signalingInnerPort"));
		signalling.setSignalingIP(object.getString("signalingIP"));
		signalling.setSignalingPort(object.getInteger("signalingPort"));
		signalling.setSignalingEnableSSL(object.getString("signalingEnableSSL"));
		signalling.setSignalingSSLCertAbsolutePath(object.getString("signalingSSLCertAbsolutePath"));
		signalling.setSignalingSSLKeyAbsolutePath(object.getString("signalingSSLKeyAbsolutePath"));
		signalling.setEnbaled(object.getString("enabled"));
		Cache.signalling = signalling;
		stop();
	}

	public void stop() {
		if (signallingServer != null) {
			signallingServer.stop();
		}
	}
	
	public void destroy() {
		if (signallingServer != null) {
			signallingServer.destroy();
		}
	}
	
	

	public int getStatus() {
		if (signallingServer != null) {
			return signallingServer.getStatus();
		}
		return -1;
	}

	public boolean verify(JSONObject object) {

		if (object == null) {
			return false;
		}

		if (!object.containsKey("signalingIP") || StrKit.isBlank(object.getString("signalingIP"))) {
			return false;
		}
		if (!object.containsKey("signalingInnerIP") || StrKit.isBlank(object.getString("signalingInnerIP"))) {
			return false;
		}
		if (!object.containsKey("signalingPort") || StrKit.isBlank(object.getString("signalingPort"))) {
			return false;
		}
		if (!object.containsKey("signalingInnerPort") || StrKit.isBlank(object.getString("signalingInnerPort"))) {
			return false;
		}

		return true;
	}

}
